package com.common.util;

import cn.hutool.json.JSONUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.Map;

/**
 *  阿里云SMS短信服务工具类
 */
public class SmsUtil {

    private final static String accessKeyId = "xxxxxxxxxxxxxxxxxxxxxxxx";
    private final static String accessKeySecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    private final static String templateCode = "SMS_154950909";

    /**
     * 发送短信验证码
     * @param phone        接收短信的手机号
     * @param codeMap      验证码map 集合
     */
    public static Boolean sendMessage(String phone,Map<String, Object> codeMap) {
        // 连接阿里云，三个参数：regionId 默认使用官方的；自己的用户accessKeyId；自己的用户accessSecret。
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        // 构建请求：
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        // 自定义参数：
        request.putQueryParameter("PhoneNumbers", phone);// 手机号
        request.putQueryParameter("SignName", "阿里云短信测试");// 短信签名
        request.putQueryParameter("TemplateCode", templateCode);// 短信模版CODE，需要和短信签名对应
        // 构建短信验证码
        request.putQueryParameter("TemplateParam", JSONUtil.toJsonStr(codeMap));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
